package manage.run;

import m.appserver.AppServerUtil;
import m.common.model.util.ModelUpdateUtil;
import m.system.RuntimeData;
import m.system.SystemInitRun;
import m.system.db.DBManager;
import m.system.db.TransactionManager;
import m.system.util.StringUtil;
import m.system.util.SystemUtil;
import manage.model.MenuInfo;
import manage.model.ModuleInfo;
import org.apache.poi.util.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class ModuleInitRun extends SystemInitRun {
	public void init() {
		RuntimeData.addTaskClass("manage.run.ServerTask|0 * * * * ?");
		RuntimeData.addActionPack("manage.action");
		RuntimeData.addActionPack("flow.action");//流程相关
		RuntimeData.addActionPack("api.action");//api相关
		RuntimeData.addModelPack("manage.model");
		RuntimeData.addModelPack("flow.model");//流程相关
		RuntimeData.addModelPack("api.model");//api相关
		RuntimeData.addHandlerPack("m.system.handler");
		RuntimeData.addStaticField("ImageInfo.imgPath","ImageInfo.thumPath","IconInfo.path");
		RuntimeData.addSecretField("AdminLogin.password","AdminLogin.token");
	}

	private static String adminRemind;
	private static String adminPage;
	private static String loginPage;
	private static String registerPage;
	private static String findPasswordPage;
	private static List<String[]> powerList;
	public void run(boolean isMain) {
		InputStream is = AppServerUtil.loadConfig("config/module.xml");
		DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
		DocumentBuilder dombuilder;
		TransactionManager tm=new TransactionManager();
		try {
			tm.begin();
			if(isMain) clearModuleMenu();//清除现有菜单,重新插入
			dombuilder = domfac.newDocumentBuilder();
			Document doc=dombuilder.parse(is);
			Element root=doc.getDocumentElement();
			adminPage=getNodeContent(root.getAttributes().getNamedItem("adminPage"),"page/index.html");
			loginPage=getNodeContent(root.getAttributes().getNamedItem("loginPage"),"action/manage/adminLogin/toLogin");
			registerPage=getNodeContent(root.getAttributes().getNamedItem("registerPage"));
			findPasswordPage=getNodeContent(root.getAttributes().getNamedItem("findPasswordPage"));
			adminRemind=getNodeContent(root.getAttributes().getNamedItem("adminRemind"));
			NodeList moduleList=root.getChildNodes();
            for (int i = 0; i < moduleList.getLength(); i++) {
                Node module = moduleList.item(i);
                if (null == module.getAttributes()) continue;
                if ("power".equals(module.getNodeName())) {
                    initPowerAttribute(module);
                } else if ("module".equals(module.getNodeName())) {
                    if (!isMain) continue;
                    ModuleInfo mi = new ModuleInfo();
                    mi.setOid(getNodeContent(module.getAttributes().getNamedItem("oid")));
//mi=ModelQueryUtil.getModel(mi);
                    mi.setName(getNodeContent(module.getAttributes().getNamedItem("name")));
                    mi.setType(getNodeContent(module.getAttributes().getNamedItem("type")));
                    if (StringUtil.isSpace(mi.getType())) mi.setType("A");
                    mi.setSort(Integer.parseInt(getNodeContent(module.getAttributes().getNamedItem("sort"))));
                    mi.setUrlPath(getNodeContent(module.getAttributes().getNamedItem("urlPath")));
                    mi.setIsPublic(getNodeContent(module.getAttributes().getNamedItem("isPublic")));
                    mi.setIcoStyle(getNodeContent(module.getAttributes().getNamedItem("icoStyle")));
                    mi.setIsInput("N");
                    ModelUpdateUtil.insertModel(mi);
                    updateMenu(module, mi, null);
                }
            }
            tm.commit();
		} catch (Exception e) {
			tm.rollback();
			//throw new MException(ModuleInitRun.class,"初始化模块菜单出错!"+e.getMessage());
			SystemUtil.printlnIf(true,"初始化模块菜单出错!");
			e.printStackTrace();
		}finally {
			TransactionManager.closeConnection();
		}
		IOUtils.setByteArrayMaxOverride(300000000);
	}
	private void clearModuleMenu() throws SQLException{
		DBManager.executeUpdate("DELETE FROM os_module_info WHERE is_input='N'");
		DBManager.executeUpdate("DELETE FROM os_menu_info WHERE is_input='N'");
	}
	private void updateMenu(Node module,ModuleInfo moduleObj,MenuInfo menuObj) throws Exception{
		NodeList menuList=module.getChildNodes();
		if(menuList!=null){
			for(int i=0;i<menuList.getLength();i++){
				Node menu=menuList.item(i);
				if(null==menu.getAttributes()) continue;
				MenuInfo mi=new MenuInfo();
				mi.setOid(getNodeContent(menu.getAttributes().getNamedItem("oid")));
				//mi=ModelQueryUtil.getModel(mi);
				mi.setName(getNodeContent(menu.getAttributes().getNamedItem("name")));
				mi.setSort(Integer.parseInt(getNodeContent(menu.getAttributes().getNamedItem("sort"))));
				mi.setUrlPath(getNodeContent(menu.getAttributes().getNamedItem("urlPath")));
				mi.setIsPublic(getNodeContent(menu.getAttributes().getNamedItem("isPublic")));
				mi.setIcoStyle(getNodeContent(menu.getAttributes().getNamedItem("icoStyle")));
				mi.setDescription(getNodeContent(menu.getAttributes().getNamedItem("description")));
				mi.setModuleInfo(moduleObj);
				if(null!=menuObj){
					mi.setParentMenu(menuObj);
				}
				mi.setIsInput("N");
				ModelUpdateUtil.insertModel(mi);
				updateMenu(menu,moduleObj,mi);
			}
		}
	}
	private String getNodeContent(Node node){
		if(null==node){
			return "";
		}else{
			return node.getTextContent();
		}
	}
	public String getNodeContent(Node node,String defaultValue){
		String value=getNodeContent(node);
		if(StringUtil.isSpace(value)) return defaultValue;
		else return value;
	}
	private void initPowerAttribute(Node module){
		powerList= new ArrayList<>();
		NodeList menuList=module.getChildNodes();
		if(menuList!=null){
			for(int i=0;i<menuList.getLength();i++){
				Node operation=menuList.item(i);
				if(null==operation.getAttributes()) continue;
				powerList.add(new String[]{
					getNodeContent(operation.getAttributes().getNamedItem("name")), 
					getNodeContent(operation.getAttributes().getNamedItem("title"))+"|"+getNodeContent(operation.getAttributes().getNamedItem("description"))
				});
			}
		}
	}
	public static List<String[]> getPowerList() {
		return powerList;
	}
	public static String getAdminPage() {
		return adminPage;
	}
	public static String getAdminRemind() {
		return adminRemind;
	}

	public static String getLoginPage() {
		return loginPage;
	}

	public static String getRegisterPage() {
		return registerPage;
	}

	public static String getFindPasswordPage() {
		return findPasswordPage;
	}
}
